<template>
  <n-affix :top="0">
    <n-flex
      style="
        width: calc(100vw - 20px);
        justify-content: center;
        margin: 0 auto;
        background-color: #ffffff;
        padding: 10px 0;
      "
    >
      <n-tag
        v-for="item in sitesStore.tags"
        :key="item.key"
        :checked="item.key === activeTag"
        checkable
        round
        style="--n-color-checkable: rgb(250, 250, 252)"
        @update:checked="tagChange(item)"
        @contextmenu.prevent="
          handleContextMenu({
            e: $event,
            item,
          })
        "
      >
        {{ item.name }}
      </n-tag>
    </n-flex>
    <div></div>
  </n-affix>

  <n-dropdown
    placement="bottom-start"
    trigger="manual"
    :x="xRef"
    :y="yRef"
    :options="options"
    :show="showDropdown"
    @clickoutside="showDropdown = false"
    @select="showDropdown = false"
  />
</template>
<script setup lang="ts">
import { useDialog } from 'naive-ui'
import { useSites } from '@/stores/sites'
import { nextTick, ref } from 'vue'
const sitesStore = useSites()

const activeTag = defineModel()
function tagChange(tag: { key: string }) {
  activeTag.value = tag.key === activeTag.value ? '' : tag.key

  if (!activeTag.value) return
  const el = document.getElementById(tag.key)
  if (!el) return
  el.parentElement!.scrollTo({
    top: el.offsetTop - 80,
    behavior: 'smooth',
  })
}

const dialog = useDialog()

let data: any
const options = [
  {
    label: '删除',
    key: 'delete',
    props: {
      onClick: () => {
        dialog.warning({
          title: '警告',
          content: '确认删除？',
          positiveText: '删除',
          negativeText: '算了',
          onPositiveClick: () => {
            const tags = [...sitesStore.tags]
            const index = tags.findIndex((item: any) => item.key === data.key)
            tags.splice(index, 1)
            return sitesStore.setTags(tags).then(() => {
              const sites = [...sitesStore.sites]
              sites.forEach((site: any) => {
                if (!site.tags?.length) return
                const index = site.tags.findIndex((item: any) => item === data.key)
                if (index === -1) return
                site.tags.splice(index, 1)
              })
              sitesStore.setSites(sites)
            })
          },
        })
      },
    },
  },
]
const showDropdown = ref(false)
const xRef = ref(0)
const yRef = ref(0)
function handleContextMenu(opt: { e: MouseEvent; item?: any }) {
  data = opt.item
  showDropdown.value = false
  nextTick().then(() => {
    showDropdown.value = true
    xRef.value = opt.e.clientX
    yRef.value = opt.e.clientY
  })
}
</script>
<style scoped>
.n-affix--affixed {
  box-shadow: 0px 1px 12px rgba(0, 0, 0, 0.12);
}
</style>
